package com.kay.server;

import com.kay.mapper.Mapper;
import com.kay.mapper.MapperData;

import java.net.Socket;

/**
 * @Description:
 * @Author: Kay
 * @CreateDate: 2021/8/3$ 11:45$
 * @UpdateUser: Kay
 * @UpdateDate: 2021/8/3$ 11:45$
 */
public class RequestProcessor extends Thread {
    private Socket socket;
    //    private Map<String, HttpServlet> servletMap = new HashMap<>();
    private Mapper mapper;

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try {
            Request request = new Request(socket.getInputStream(), mapper);
            String url = request.getUrl();
            System.out.println(" url _____________ " + url);
            System.out.println(" method _____________ " + request.getMethod());
            Response response = new Response(socket.getOutputStream());
            MapperData mapperData = request.getMapperData();
            if (mapperData.wrapper == null) {
//                response.outputStaticResources(url);
                if (mapperData.host != null){
                    String absolutePath = mapperData.host.getAppBase() + url;
                    System.out.println(" =================>>>> absolutePath : " + absolutePath);
                    response.outputStaticResourcesByAbsolutePath(absolutePath);
                }else {
                    response.outputContent(HttpProtocolUtils.getContent404());
                }
            } else {
                mapperData.wrapper.getObject().service(request, response);
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
